source('base.R')

write_session <- function(session_break, data, session_file) {
    session <- data[session_break[1]:session_break[2],]
    session_id <- paste(session_break[1], session_break[2], sep=':')
    session$session_id <- paste(session$user_id, session_id, sep='-')
    write.table(session, file=session_file, quote=FALSE, sep=',', row.names=FALSE, col.names=FALSE)
}

split_session <- function(data, session_file) {
    rev_intvl <- rev(c(-Inf, diff(rev(data$time))))
    breaks <- c(0, which(rev_intvl<rev_intvl_threshold))
    n <- length(breaks)
    session_breaks <- cbind(breaks[1:(n-1)]+1, breaks[2:n])
    apply(session_breaks, MARGIN=1, FUN=write_session, data=data, session_file=session_file)
}

get_ending_seq <- function(action, ending_length) {
    n <- length(action)
    step <- ending_length - 1
    ifelse(n<ending_length, ending_act<-action, ending_act<-action[(n-step):n])
    ending_seq <- paste(ending_act, collapse='-')
    return(ending_seq)
}

group_analyse <- function(data) {
    seq <- levels(factor(data$ending_seq))
    pop <- nlevels(factor(data$user_id))
    count <- nrow(data)
    sat <- median_sat(data)
    dur <- median_dur(data)
    avg <- action_avg(data)
    ratio <- action_ratio(data)

    print(seq)
    print(pop)
    print(count)
    print(sat)
    print(dur)
    print(avg)
    print(ratio)
}

run <- function(log_filename, profile_filename, session_filename, output_filename) {
    log <- read(log_filename)
    profile <- read(profile_filename)

    log <- filter(log, 3)

    session_file <- file(session_filename, 'a')
    by(log, INDICE=log$user_id, FUN=split_session, session_file=session_file)
    close(session_file)

    data <- read(session_filename, header=c(colnames(log), 'session_id'))
    ending_seq <- tapply(data$action, INDEX=data$session_id, FUN=get_ending_seq, ending_length=3)
    data$ending_seq <- ending_seq[data$session_id]

    count <- tapply(data$session_id, INDEX=data$ending_seq, FUN=function(data) nlevels(factor(data)))

    sink(output_filename)
    
    print(count)

    data$count <- count[data$ending_seq]
    major_session <- data[data$count>=5000,]
    major_data <- major_session[c(colnames(log),'ending_seq'),]
    by(major_data, INDICE=major_data$ending_seq, FUN=group_analyse)

    sink()
}

run('data/daily_log_2011-04-13',
    'data/user_profile_2011-04-14_10',
    'ending_seq_analyse.temp',
    'ending_seq_analyse.output')
